<template>
  <div>
    <el-space direction="vertical" alignment="normal" style="width: 100%">
      <el-card>
        <!--根据用户名、电话、状态搜索的内容绑定在searchForm里面，用于后续向后端要数据-->
        <el-form ref="searchFormComponents" :model="searchForm" inline>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="searchForm.username" clearable></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="tel">
            <el-input v-model="searchForm.tel" clearable></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status" >

            <el-select v-model="searchForm.status" placeholder="select" clearable filterable style="width: 150px">
              <el-option :label="item" :key="item" :value="item" v-for="item in statusList"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
            <el-button type="primary" :icon="Refresh" @click="resetSearch">重置</el-button>

          </el-form-item>
        </el-form>

        <el-space>
          <el-button type="primary" :icon="Plus" @click="add">添加</el-button>
          <el-button type="danger" :disabled="selectionRows.length <= 0" :icon="Delete " @click="batchDelete(null)">批量删除</el-button>
        </el-space>

      </el-card>
      <el-card>
<!--        //table表单与listData绑定，一开始listData里面是空的，当用getPList方法后，里面就会有数据，然后用于表单，selectionChange里面绑定的是被选中的数据-->
        <el-table :data="listData" style="width: 100%" @selection-change="selectionChange" ref="tableComponents" border>
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column property="id" label="ID"></el-table-column>
          <el-table-column property="username" label="用户名" width="120"></el-table-column>
          <el-table-column property="nickname" label="昵称"></el-table-column>
          <el-table-column property="avatarUrl" label="头像">
                <template #default="scope">
                  <el-image v-if="scope.row.avatarUrl" style="width: 100px;height:100px" :src="scope.row.avatarUrl" :preview-src-list="[formData.avatarUrl]" :preview-teleported="true">

                  </el-image>
                </template>
          </el-table-column>
          <el-table-column property="tel" label="电话"></el-table-column>
          <el-table-column property="email" label="邮箱"></el-table-column>
          <el-table-column property="status" label="状态"></el-table-column>
          <el-table-column property="createTime" label="创建时间" width="170"></el-table-column>
          <el-table-column fixed="right" label="权限操作" width="140">
            <template #default="scope">
              <el-button type="success" :icon="RefreshLeft" @click="resetPassword(scope.row)">重置密码</el-button>
            </template>
          </el-table-column>


          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
<!--              //scope.row表示的是表单中当前的这一行数据-->
              <el-button type="primary" :icon="Edit" @click="edit(scope.row)">编辑</el-button>
              <el-button type="danger" :icon="Delete " @click="oneDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
<!--页面选择-->
        </el-table>
        <div style="margin-top: 20px">
          <el-pagination
              @current-change="currentChange"
              @size-change="sizeChange"
              :page-size="pageInfo.pageSize"
              :current-page="pageInfo.pageNo"
              size="small"
              background
              layout="total,sizes,prev, pager, next"
              :total="pageInfo.total"
          />
        </div>

      </el-card>

    </el-space>
<!--弹出一个填写界面，如果formData.id里面有值就是编辑否则就是添加-->
    <el-dialog v-model="dialogOpen" v-if="dialogOpen" :title="formData.id?'编辑':'添加'" width="500">
<!--      与formData双向绑定，如果formData里面有值，formData里面的值就直接显示在编辑页面，就不必修改-->
      <el-form ref="formRef" :model="formData" label-width="100">
        <el-form-item label="用户名" prop="username" :rules="[{required:true,message:'不能为空',trigger:['blur','change']}]">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="nickname" :rules="[{required:true,message:'不能为空',trigger:['blur','change']}]">
          <el-input v-model="formData.nickname"></el-input>
        </el-form-item>

        <el-form-item label="头像" prop="" :rules="[{required:true,message:'不能为空',trigger:['blur','change']}]">
          <MyUpload type="imageCard" :limit="1" :files="formData.avatarUrl" @setFiles="formData.avatarUrl = $event" v-if="dialogOpen">

          </MyUpload>
        </el-form-item>

        <el-form-item label="电话" prop="tel" :rules="[{required:true,message:'不能为空',trigger:['blur','change']}]">
          <el-input v-model="formData.tel"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" :rules="[{required:true,message:'不能为空',trigger:['blur','change']}]">
          <el-input v-model="formData.email"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status" :rules="[{required:true,message:'不能为空',trigger:['blur','change']}]">
          <el-radio-group v-model="formData.status">
            <el-radio v-for="item in statusList" :key="item" :value="item">{{item}}</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button type="primary" :icon="Check" @click="commit">提交</el-button>
        <el-button type="" :icon="Close" @click="closedialog">取消</el-button>
      </template>

    </el-dialog>


  </div>
</template>

<script setup>

import {Check, Close, Delete, Edit, Plus, Refresh, RefreshLeft, Search} from "@element-plus/icons-vue";
  import request from "@/utils/http.js"
  import {ref, toRaw} from "vue";
  import MyUpload from "@/components/MyUpload.vue";
  import {ElMessage, ElMessageBox} from "element-plus";

  const searchFormComponents = ref()
// 用来双向绑定搜索框里面的值，拿到后向后端发起请求搜索
  const searchForm = ref({
    username:undefined,
    tel:undefined,
    status:undefined
  })

  const statusList = ref(['启用','禁用'])
// 用来接收从后端拿到的数据，然后用于绑定表单
  const listData = ref([
    {
      username:"张三",
      nickname:"zhangsan"
    }
  ])
// 与searchForm配合向后端请求的传参
  const pageInfo = ref({
    //当前页
    pageNo:1,
    //每页的条数
    pageSize:10,
    //总条数
    total:0
  })
// formData里面一开始是空的，用来与下拉界面双向绑定，当点击编辑按钮时，调用edit这个方法，这个方法里面的formData.value = Object.assign({},row)会自动将当前那一栏的数据赋值给formData
//     这样下界面就可以通过formData.id的值判断是编辑还是添加
  const formData = ref({})
//下拉界面是否打开，一开始是false表示默认不打开，当点击编辑或者添加按钮时，调用相应的方法会将false改成true
  const dialogOpen = ref(false)

  const formRef = ref()
// 里面放的是选中的那一栏表单
  const selectionRows = ref([])

  const tableComponents = ref()

       getPList();

  function getPList(){
    //向后端发起请求 带参数 分页参数以及搜索参数
    request.get("/user/page",{
      params:Object.assign(toRaw(searchForm.value),toRaw(pageInfo.value))
    }).then(res => {
      listData.value = res.data.list
      pageInfo.value.total = res.data.total

    })
  }
  // 搜索按钮调用的方法
  function search(){
      pageInfo.value.pageNo = 1
      getPList()

  }
  // 重置搜索
  function resetSearch(){
      searchFormComponents.value.resetFields()
      getPList()
  }
  function currentChange(num){
    pageInfo.value.pageNo = num;
    getPList()
  }
  function sizeChange(num){
    pageInfo.value.pageSize = num;
    getPList()
  }
  function add(){
    formData.value = {}

    dialogOpen.value = true
  }
  function edit(row){
    formData.value = Object.assign({},row)
    dialogOpen.value = true
  }
  function selectionChange(rows){
    selectionRows.value = rows
  }
  function batchDelete(rows){
    //这条if语句是用来与oneDelete配合使用，当oneDelete中没有调用batchDelete的方法时，也就是rows没有被传参数
    if(!rows){
        rows = selectionRows.value
    }
    const ids = rows.map(item => item.id)

    ElMessageBox.confirm(
        `此操作将永久删除ID为[${ids}]的数据，是否继续`,
        'Warning',
        {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning',
          center: true,
        }
    )
        .then(() => {
          request.delete("/user/delete" , {data:ids}).then(()=>{
            ElMessage({
              type: 'success',
              message: 'Delete completed',
            })
            getPList()
          })


        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: 'Delete canceled',
          })
          //取消按钮的时候，自动取消表格的选中
          tableComponents.value.clearSelection()
        })
  }
  function oneDelete(row){
      batchDelete([row])
  }
  function commit(){
    formRef.value.validate((valid)=>{
      if(!valid){
        ElMessage({
          message:"验证失败，请检查表单",
          type:'warning'
        })
        return
      }
      const requestMethod = formData.value.id?request.put : request.post
      const url = formData.value.id ? "/user/update" : "/user/add"
      requestMethod(url,formData.value).then(res => {
        dialogOpen.value = false
        ElMessage({
          message:res.msg,
          type:'success'
        })
        getPList()
      })
    } )
  }
  function closedialog(){
      dialogOpen.value = false
  }
  function resetPassword(row){
    request.post("/common/resetPassword?type=USER&id="+row.id).then(res=>{
      ElMessage({
        message:'操作成功',
        type:'success'
      })
    })
  }
</script>
